
class OrderManager {
    constructor(app) {
        this.app = app;
    }
    
    async getOrderById(orderid, options) {
        // if (!(!!options && options.force)) {
        //     let userjson = await this.app.redis.client.getAsync(`glueuid_${uid}`);
        //     if (!!userjson) {
        //         try {
        //             let _user = JSON.parse(userjson);
        //             return _user
        //         } catch (e) { }
        //     }
        // }
        const User = this.app.db.User;
        let order = await this.app.db.Order.findOne({ where: { id: orderid },include:[User]}) //include: [UserProfile, Passport, Role, Corp]
        return JSON.parse(JSON.stringify(order));
    }
    async getPayedOrderByUser(uid) {
        const User = this.app.db.User;
        let order = await this.app.db.Order.findAndCountAll({ where: { uid: uid,pay_status:2 },include:[User]}) //include: [UserProfile, Passport, Role, Corp]
        return JSON.parse(JSON.stringify(order));
    }
    async saveOrder(order,user) {
        const moment = require("moment");
        let extra_field = {
            "order_sn": `dj_${moment().format('YYYYMMDDHHmmss')}_${Math.floor(Math.random()*10000)}`,
            "order_status":0,
            "shipping_status": 0,
            "pay_status": 0,
            "uid":user.id
        }; 
        let order_final = Object.assign({}, order, extra_field);
        let result_order = await this.app.db.Order.create(order_final);
        return JSON.parse(JSON.stringify(result_order));
    }
    async payCallBack(data){
        let transNo = data.tradeNoOut;
        let order = await this.app.db.Order.findOne({where:{order_sn:transNo}})
        if(!order){
            return {
                status:"error",
                message:"订单不存在"
            }
        }else{
            await order.update({pay_status:2,transNoSys:data.tradeNoSys,transNoMch:data.tradeNoFrom})
            return {
                status:"success"
            }
        }
    }
    
}
module.exports = app => {
    return new OrderManager(app)
};
